<?php

namespace App\Http\Controllers\Web;

use App\Api\Serializer\CustomSerializer;
use App\Http\Controllers\BaseController;
use App\Http\Requests\Web\UserRequest;
use App\Models\User;
use App\Transformers\UserTransformer;
use Illuminate\Http\Request;

class UserController extends BaseController
{
    public function userinfo(Request $request){
        $id = $request->id;
        $user = auth('api')->user()->id;
        if ($id){
        if ($id!=$user){
            if (!User::find($id)){
                return $this->response->errorBadRequest('没有您要查看的用户。');
            }
            $user = cache()->remember('users_info'.$id, 120, function ()use($id) {$user = User::find($id);return $user;});
            return $this->response->item($user,new UserTransformer(),function ($resource, $fractal) {
                $fractal->setSerializer(new CustomSerializer());
            });

        }}
        return $this->response->item(auth('api')->user(),new UserTransformer(),function ($resource, $fractal) {
            $fractal->setSerializer(new CustomSerializer());
        });
    }
    public function avatar_change(Request $request){
        $request->validate(['avatar'=>'required'],[
            'avatar.required'=>'头像链接 不能为空'
        ]);
        $id = auth('api')->user()->id;
        cache()->forget('users_info'.$id);
        User::find($id)->update([
            'avatar'=>$request->avatar
        ]);

        return $this->response->created();
    }
    public function info_change(UserRequest $request){
        $name = $request->input('name');
        $user = auth('api')->user();
        $sex = $request->input('sex');
        $home = $request->input('home');
        $sel_show = $request->input('sel_show');
        $birthday = $request->input('birthday');
        $in = [
            'name' => $name,
            'sex'=>$sex,
            'home'=>$home,
            'birthday' => $birthday,
            'sel_show'=>$sel_show,

        ];
        cache()->forget('users_info'.$user->id);
        User::find($user->id)->update($in);
        return $this->response->created();

    }


    }
